<template>
  <div class="student-edit">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 500px; margin: 0 auto"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" maxlength="20" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" maxlength="32" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" maxlength="20" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" type="number" min="0" max="120" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDay">
          <el-date-picker
            v-model="form.birthDay"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" maxlength="20" />
        </el-form-item>
        <el-form-item label="年级" prop="userLevel">
          <el-select v-model="form.userLevel" placeholder="请选择年级">
            <el-option
              v-for="(label, value) in levelMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
          <el-button :disabled="loading" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const formRef = ref();

const loading = ref(false);
const isEdit = computed(() => !!route.query.id);

const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const form = reactive({
  id: null as number | null,
  userName: "",
  password: "",
  realName: "",
  age: undefined as number | undefined,
  sex: undefined as number | undefined,
  birthDay: "" as string,
  phone: "",
  userLevel: undefined as number | undefined,
  status: 1,
});

let originalData: any = null; // 用于重置

const rules = computed(() => ({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: isEdit.value ? [] : [{ required: true, message: "请输入密码", trigger: "blur" }],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  userLevel: [{ required: true, message: "请选择年级", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
}));

async function fetchDetail(id: number) {
  loading.value = true;
  try {
    // 后端返回示例：{ code:1, message:'成功', response:{...实际数据...} }
    const res: any = await UserAPI.getStudentDetail(id);
    console.log("res:", res);
    const data = res;

    if (!data || typeof data !== "object" || !data.id) {
      ElMessage.warning("未获取到学生详情");
      return;
    }

    // 映射数据到表单
    form.id = data.id ?? id;
    form.userName = data.userName ?? "";
    form.password = ""; // 不回显密码
    form.realName = data.realName ?? "";
    form.age = data.age !== undefined ? Number(data.age) : undefined;
    form.sex = data.sex !== undefined ? Number(data.sex) : undefined;
    form.birthDay = data.birthDay
      ? String(data.birthDay).split(" ")[0]
      : data.birthday
        ? String(data.birthday).split(" ")[0]
        : "";
    form.phone = data.phone ?? "";
    form.userLevel = data.userLevel !== undefined ? Number(data.userLevel) : undefined;
    form.status = data.status !== undefined ? Number(data.status) : 1;

    // 备份原始数据用于重置
    originalData = { ...form };
  } catch (e: any) {
    console.error("fetchDetail error", e);
    ElMessage.error(e?.message || "获取学生详情失败");
  } finally {
    loading.value = false;
  }
}

async function handleSubmit() {
  const valid: boolean = await new Promise((resolve) => {
    formRef.value?.validate((v: boolean) => resolve(v));
  });
  if (!valid) return;

  loading.value = true;
  try {
    const payload = { ...form };
    if (isEdit.value) {
      await UserAPI.editStudent({ ...payload, id: form.id! });
      ElMessage.success("更新成功");
    } else {
      await UserAPI.addStudent(payload);
      ElMessage.success("新增成功");
    }
    router.back();
  } catch (e: any) {
    console.error("submit error", e);
    ElMessage.error(e?.message || "提交失败");
  } finally {
    loading.value = false;
  }
}

function handleReset() {
  if (isEdit.value && originalData) {
    Object.assign(form, originalData);
  } else {
    Object.assign(form, {
      id: null,
      userName: "",
      password: "",
      realName: "",
      age: undefined,
      sex: undefined,
      birthDay: "",
      phone: "",
      userLevel: undefined,
      status: 1,
    });
  }
}

onMounted(() => {
  if (isEdit.value) {
    const id = Number(route.query.id);
    if (!Number.isNaN(id)) {
      fetchDetail(id);
    } else {
      ElMessage.warning("无效的学生ID");
    }
  } else {
    originalData = { ...form };
  }
});
</script>

<style scoped lang="scss">
.student-edit {
  padding: 32px 0;
}
</style>
